package model

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
	"strconv"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/pkg/drive/db"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

// 获取到 结算的结点数
// from [ 2 => Linux,  3 => Router, 1 => Pc ] 新的公式
func GetMgPaymentNodeNums(tag, From int) (res int, err error) {

	if tag == 1 {
		if From == 3 {
			err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
				" `date`=DATE_SUB(CURDATE(),INTERVAL 2 DAY) and cvn > 0 and pledge_status=1 and `type` = 3 ")
		} else {
			err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
				" `date`=DATE_SUB(CURDATE(),INTERVAL 2 DAY)  and cvn > 0 and pledge_status=1 and `type` <> 3 ")
		}
		if err != nil {
			return res, err
		}
		e.Log("err", "结算中采用前天的数据")
		return res, nil
	}

	if From == 3 {
		err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
			" `date`=DATE_SUB(CURDATE(),INTERVAL 1 DAY) and cvn > 0 and pledge_status=1 and `type` = 3 ")
	} else {
		err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
			" `date`=DATE_SUB(CURDATE(),INTERVAL 1 DAY) and cvn > 0 and pledge_status=1 and `type` <> 3 ")
	}

	if err != nil {
		return res, err
	}

	if res == 0 {
		if From == 3 {
			e.Log("info", "采用新矿池结点数")
			err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
				" `date`=DATE_SUB(CURDATE(),INTERVAL 2 DAY) and cvn > 0 and pledge_status=1 and `type` = 3 ")
		} else {
			e.Log("info", "采用旧矿池结点数")
			err = sqlx.Get(config.C.DB.DB, &res, "SELECT count(*) FROM mg_node_payment WHERE "+
				" `date`=DATE_SUB(CURDATE(),INTERVAL 2 DAY) and cvn > 0 and pledge_status=1 and `type` <> 3 ")
		}
		if err != nil {
			return res, err
		}
		e.Log("info", "矿池结点数=", res)
		e.Log("err", "非结算中采用前两天的数据")
	} else {
		e.Log("info", "矿池结点数=", res)
		e.Log("err", "非结算中采用昨天的数据")
	}

	return
}

// 校验是否已经存在记录
func CheckMgNodePaymentRecord(NodeId int64, Type, Source int, DateStr string) (err error) {

	var rId int64
	err = sqlx.Get(config.C.DB.DB, &rId, "SELECT id from mg_node_payment WHERE node_id =? AND `type` = ? "+
		" AND `source` =? AND `date` =? ", NodeId, Type, Source, DateStr)
	if err == sql.ErrNoRows {
		return nil
	} else if err != nil {
		return err
	}

	if rId > 0 {
		return errno.ExistsRecord
	}
	return nil
}

type CheckMultipleNodeInfoResponse struct {
	DateStr      string  `json:"dateStr"`
	SuperNodeId  int64   `json:"superNodeId"`
	Up           float64 `json:"up"`
	Cvn          float64 `json:"cvn"`
	SuperCvn     float64 `json:"superCvn"`
	PledgeStatus int     `json:"pledgeStatus"`
	Status       int     `json:"status"`
	OnlineTime   int     `json:"onlineTime"`
	Uid          int64   `json:"uid"`
	NodeId       int64   `json:"nodeId"`
	Type         int     `json:"type"`
	Source       int     `json:"source"`
	SourceFlows  float64 `json:"source_flows"`
	SourceCvn    float64 `json:"source_cvn"`
	SourceRate   float64 `json:"source_rate"`
}

// 写入待结算记录表
func AddMultipleMgNodePaymentRecord(NodeData CheckMultipleNodeInfoResponse) (err error) {

	// 开启事务
	conn, err := config.C.DB.DB.Begin()
	if err != nil {
		return err
	}

	var rowId1 int64
	// 汇总流量数据以用户纬度
	r1, err1 := conn.Exec("REPLACE INTO mg_node_payment (date,uid,node_id,up,type,pledge_status,status,cvn,super_cvn,"+
		" super_node_id,online_time,create_time,source,source_flows,source_cvn,source_rate) "+
		" VALUES (?,?,?,?,?,?,?,?,?,?,?,unix_timestamp(NOW()),?,?,?,?) ",
		NodeData.DateStr, NodeData.Uid, NodeData.NodeId, NodeData.Up, NodeData.Type, NodeData.PledgeStatus, NodeData.Status,
		NodeData.Cvn, NodeData.SuperCvn, NodeData.SuperNodeId, NodeData.OnlineTime, NodeData.Source, NodeData.SourceFlows,
		NodeData.SourceCvn, NodeData.SourceRate)
	if err1 == nil {
		rowId1, err = r1.RowsAffected()
		if err != nil {
			return errno.DbError
		}
	}

	// 将流量数据状态更新为 待结算
	//r2, err2 := conn.Exec("UPDATE mg_node_flow SET status = 1 WHERE time < unix_timestamp(NOW()) AND status = 0 "+
	//	" AND node_id = ? AND type = ? AND source = ?", NodeData.NodeId, NodeData.Type, NodeData.Source)
	//if err2 == nil {
	//	rowId2, err2 = r2.RowsAffected()
	//	if err2 == nil {
	//		rowId2 = 1
	//	}
	//}

	// 提交事务
	if rowId1 > 0 {
		err = conn.Commit()
		if err != nil {
			_ = conn.Rollback()
			return errno.RollBackErr
		}
		e.Log("info", "NodeId="+strconv.FormatInt(NodeData.NodeId, 10)+" 写入结算记录表完成.")
		return nil
	} else {
		_ = conn.Rollback()
		return errno.RollBackErr
	}
}

// 获取指定用户昨日收益
func GetTheUsrLastCvn(Uid int64) (cvn float64, err error) {

	err = sqlx.Get(config.C.DB.DB, &cvn, "SELECT sum(cvn) as cvn FROM mg_node_payment where uid = ? "+
		" and date= DATE_SUB(CURDATE(),INTERVAL 1 DAY)", Uid)
	if err != nil {
		return cvn, err
	}
	return cvn, nil
}

// 更新收益发放记录
func UpdateMgUserPaymentData(conn *db.TxLogger, LxLogId int64) (err error) {
	var rowId3 int64
	r3, err3 := conn.Exec("UPDATE mg_user_payment SET `status` = 3 WHERE id = ? AND `status` = 2", LxLogId)
	if err3 == nil {
		rowId3, err3 = r3.RowsAffected()
		if rowId3 <= 0 {
			rowId3 = 1
		}
	} else {
		return err
	}
	if rowId3 > 0 {
		return nil
	}
	return errno.DbDataError
}
